package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import com.example.myapplication.utils.HttpRequestUtil;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class MainAbilitySlice extends AbilitySlice {

    String result = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Text text = findComponentById(ResourceTable.Id_result_text);

        Button btn1 = findComponentById(ResourceTable.Id_btn1);
        btn1.setClickedListener(component -> {
            //如果在此进行网络访问，会报错（不能在主线程中进行网络访问）
            //原因：移动应用中不允许在主线程中运行耗时的程序
            //解决：将耗时的操作放在一个独立的线程中完成，主线程就不会被阻塞
            //方法：创建TaskDispatcher对象
            //参数TaskPriority:线程优先级，default表示默认
            TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            //globalTaskDispatcher.syncDispatch();//同步线程分发，见官方文档
            //globalTaskDispatcher.asyncDispatch();//异步线程分发
            globalTaskDispatcher.asyncDispatch(() -> {
                //访问网络接口
                String urlString = "https://api.muxiaoguo.cn/api/Gushici";

                //将访问网络结构的代码放在工具类中，方便引用
                result = HttpRequestUtil.sendGetRequest(this,urlString);
                System.out.println("-------》》》访问网络接口返回的结果是:" + result);

                //因为api接口访问data传值需要json格式，获取的结果也是json格式，所以需要Java对象<--->json字符串转换
                //Gson
                //jackson  ObjectMapper
                //引入第三方依赖,要不然无法创建下列对象
                //在build.gradle里边的依赖里面添加
                Gson gson = new Gson();


            });

        });

        text.setClickedListener(component -> {
            text.setText("返回的结果是:" + result);
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
